package cn.time1024.time_app.ui.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import cn.time1024.time_app.R
import cn.time1024.time_app.databinding.FragmentHomeBinding
import androidx.recyclerview.widget.GridLayoutManager

/**
 * 首页 Fragment：展示首页文案与功能菜单（工作流、菜单二、菜单三）。
 * - 负责菜单点击后的导航到对应功能页面。
 */
class HomeFragment : Fragment() {
    private lateinit var homeViewModel: HomeViewModel
    private var _binding: FragmentHomeBinding? = null
    private val binding get() = _binding!!

    /**
     * 创建并返回首页视图，同时初始化ViewBinding与首页文案。
     */
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        homeViewModel = ViewModelProvider(this)[HomeViewModel::class.java]

        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        setupHeader()
        setupQuickOverview()
        setupFunctionMenu()
        setupCards()
        setupFab()
        return binding.root
    }

    /**
     * 视图创建完成后绑定菜单点击事件，执行到对应目的地的导航。
     */
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 保留按需的额外导航（已迁移到菜单网格与卡片中）
    }

    private fun setupHeader() {
        val now = java.util.Calendar.getInstance().time
        val cal = java.util.Calendar.getInstance()
        cal.time = now
        val hour = cal.get(java.util.Calendar.HOUR_OF_DAY)
        val greeting = when {
            hour < 12 -> "早上好，小明"
            hour < 18 -> "下午好，小明"
            else -> "晚上好，小明"
        }
        val fmt = java.text.SimpleDateFormat("yyyy年MM月dd日 EEEE", java.util.Locale.CHINA)
        binding.tvGreeting.text = greeting
        binding.tvDate.text = fmt.format(now)
        binding.btnBell.setOnClickListener { findNavController().navigate(R.id.navigation_notifications) }
        binding.imgAvatar.setOnClickListener { findNavController().navigate(R.id.navigation_notifications) }
    }

    private fun setupQuickOverview() {
        binding.cardTodayTasks.setOnClickListener { findNavController().navigate(R.id.navigation_dashboard) }
        binding.cardTodayFocus.setOnClickListener { /* 番茄钟待实现 */ }
    }

    private fun setupFunctionMenu() {
        val items = listOf(
            HomeMenuItem("notebook", "记事本", R.drawable.ic_dashboard_black_24dp, "#2563eb", "#dbeafe") { findNavController().navigate(R.id.navigation_notebook) },
            HomeMenuItem("music", "音乐", R.drawable.ic_dashboard_black_24dp, "#16a34a", "#dcfce7") { findNavController().navigate(R.id.navigation_music) },
            HomeMenuItem("video", "视频", R.drawable.ic_dashboard_black_24dp, "#9333ea", "#f3e8ff") { findNavController().navigate(R.id.navigation_video_list) },
            HomeMenuItem("account", "记账", R.drawable.ic_dashboard_black_24dp, "#ea580c", "#fed7aa") { findNavController().navigate(R.id.navigation_account_manage) },
            HomeMenuItem("plan", "计划", R.drawable.ic_dashboard_black_24dp, "#4f46e5", "#e0e7ff") { /* 待实现 */ },
            HomeMenuItem("pomodoro", "番茄钟", R.drawable.ic_dashboard_black_24dp, "#dc2626", "#fecaca") { /* 待实现 */ },
            HomeMenuItem("habit", "习惯", R.drawable.ic_dashboard_black_24dp, "#0d9488", "#ccfbf1") { /* 待实现 */ },
            HomeMenuItem("stats", "统计", R.drawable.ic_dashboard_black_24dp, "#6b7280", "#f9fafb") { /* 待实现 */ },
        )
        val adapter = HomeMenuAdapter(items)
        binding.rvFunctionMenu.layoutManager = GridLayoutManager(requireContext(), 4)
        binding.rvFunctionMenu.adapter = adapter
    }

    private fun setupCards() {
        binding.cardPlan.setOnClickListener { /* 待实现 */ }
        binding.btnViewAllPlans.setOnClickListener { /* 待实现 */ }
        binding.cardFinance.setOnClickListener { findNavController().navigate(R.id.navigation_account_manage) }
        binding.btnViewAllFinance.setOnClickListener { findNavController().navigate(R.id.navigation_account_manage) }
        binding.cardNews.setOnClickListener { /* 待实现 */ }
        binding.btnViewAllNews.setOnClickListener { /* 待实现 */ }
    }

    private fun setupFab() {
        binding.fabAdd.setOnClickListener {
            val items = arrayOf("添加任务", "添加计划", "添加记账")
            androidx.appcompat.app.AlertDialog.Builder(requireContext())
                .setItems(items) { _, which ->
                    when (which) {
                        0 -> findNavController().navigate(R.id.navigation_dashboard)
                        1 -> {}
                        2 -> findNavController().navigate(R.id.navigation_account_manage)
                    }
                }
                .show()
        }
    }

    /**
     * 销毁视图时释放ViewBinding，避免内存泄漏。
     */
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
